(function (window, $, undefined) {
  'use strict';

  // 标识是否有拉新数据
  var preData = null;
  var couponData = {};

  var $formPull = $('#form-pull');

  main(function () {

    // 获取所有优惠券数据
    util.get(ajaxURL.COUPON + '/coupon/v1/couponInfo/getAll', function (res) {
      var data = res.data;
      if (data && data.length > 0) {
        renderCoupon(data);
        couponData = data;
        getInfo(function () {
          $('#btn-save').off('click.save').on('click.save', savePullData);
        });
      } else {
        util.tip.warn('暂无可用代金券类型，请添加后再进行操作');
      }
    });

    // 渲染优惠券列表
    var $newList = $('#new-list');
    var $sumList = $('#sum-list');

    function renderCoupon(data) {
      var strNewList = '<ul>'; // 新人策略

      $.each(data, function (_, item) {
        strNewList += renderLi(item.kid, item.couponName);
      });

      strNewList += '</ul>';

      $newList.html(strNewList);

      util.selectHtml('select[name="couponId"]', data, 'kid', 'couponName', '请选择');
    }

    function renderLi(kid, couponName) {
      var ret = '<li class="form-inline" data-kid="' + kid + '">';
      ret += '<label title="' + couponName + '"><input class="item-id" type="checkbox" value="' + kid + '"><span class="text">' + couponName + '</span></label>';
      ret += '<input disabled class="item-quantity form-control form-width70">';
      ret += '<span class="text">张</span>';
      return ret;
    }

    // 优惠券列表点击激活后面的输入框效果
    $formPull.on('click', '.item-id', function () {
      var $this = $(this);
      var checked = $this.prop('checked');
      var $input = $this.parent().next();
      if (checked) {
        $input.removeAttr('disabled');
        if (!$input.val()) {
          $input.addClass('error');
        }
      } else {
        $input.attr('disabled', 'disabled').removeClass('error');
      }
    });

    // 拉新配置显隐相关
    var $strategyBox = $('#strategy-box');
    $formPull.on('click', '[name="strategyStatus"]', function () {
      var val = +$(this).val();
      if (val === 0) {
        $strategyBox.addClass('hide');
      } else {
        $strategyBox.removeClass('hide');
      }
    });

    // 领用送券
    var $couponSel = $('#coupon-sel');
    $couponSel.change(function () {
      var $this = $(this);
      var val = $this.val();
      var $next = $this.next();
      if (val) {
        $next.removeAttr('disabled');
      } else {
        $next.attr('disabled', 'disabled').removeClass('error').parents('.form-container').find('label.error').remove();
      }
    });

    // 获取数据
    function getInfo(callback) {
      util.get(ajaxURL.COUPON + '/coupon/v1/pullConfig/get', function (res) {
        preData = res.data;
        var data = res.data || {};
        if (data) {
          // data.couponId = 1;
          // data.couponQty = 5;
          // data.updateTime = 1514251069661
          // data.strategyStatus = 1;
          // data.couponDetailList = [{
          //   couponId: 1,
          //   couponQty: 20
          // }]
          // data.ruleList = [{
          //   pullTotal: 5,
          //   couponId: 1,
          //   couponQty: 20
          // }, {
          //     pullTotal: 4,
          //     couponId: 1,
          //     couponQty: 120
          //   }]

          util.fillForm($formPull, data);

          $sumList.empty();
          if (data.ruleList && data.ruleList.length > 0) {
            $.each(data.ruleList, function (_, item) {
              addSumItem(item);
            });
          } else {
            addSumItem();
          }

          if ($sumList.children().length === 1) {
            $sumList.children().eq(0).find('.del-sum-item').attr('disabled', 'disabled');
          }

          $formPull.find('[data-updateId]').text(data.updateBy || data.updateId || data.createId || '-');
          var updateTime = data.updateTime || data.createTime;

          $formPull.find('[data-updateTime]').text(updateTime ? util.dateFormat(updateTime) : '-');

          // 相关状态设置
          if (data.couponId) {
            $couponSel.next().removeAttr('disabled');
          }
          if (+data.strategyStatus === 1) {
            $strategyBox.removeClass('hide');
          }

          // 拉新配置
          if (data.couponDetailList && data.couponDetailList.length > 0) {
            $.each(data.couponDetailList, function (_, item) {
              var $elem = $newList.find('li[data-kid="' + item.couponId + '"]');
              $elem.find('.item-id').prop('checked', true);
              $elem.find('.item-quantity').val(item.couponQty).removeAttr('disabled');
            });
          }
          // 累计策略
          if (data.ruleList && data.ruleList.length > 0) {
            $.each(data.ruleList, function (_, item) {
              var $elem = $sumList.find('li[data-kid="' + item.couponId + '"]');
              $elem.find('.item-id').prop('checked', true);
              $elem.find('.item-quantity').val(item.couponQty).removeAttr('disabled');
            });
          }
        }

        if ($.isFunction(callback)) {
          callback();
        }

      });
    }

    $('.add-sum-item').click(function () {
      addSumItem();
      $sumList.find('.del-sum-item').removeAttr('disabled');
    });

    $sumList.on('click', '.del-sum-item', function () {
      var $this = $(this);
      var $li = $this.parent();
      layer.confirm('删除该行？', function (index) {
        layer.close(index);
        $li.remove();
        if ($sumList.children().length <= 1) {
          $sumList.find('.del-sum-item').attr('disabled', 'disabled');
        }
      });
    });

    function addSumItem(data) {
      var ret = '<li class="form-inline">';
      ret += '<input digits min="1" max="10000" class="form-control form-width70 item-sum error">';
      ret += '<span class="text marginR10">人</span>';
      ret += '<select required class="form-control form-width120 marginR10 item-coupon error">';
      ret += '<option value="">请选择</option>';
      $.each(couponData, function (_, item) {
        ret += '<option value="' + item.kid + '">' + item.couponName + '</option>';
      });
      ret += '</select>';
      ret += '<input digits min="1" max="10000" class="form-control form-width70 item-quantity error">';
      ret += '<span class="text marginR10">张</span>';
      ret += '<button class="btn btn-default del-sum-item" type="button"><i class="fa fa-trash-o"></i><span>删除</span></button>';
      ret += '</li>';
      var $ret = $(ret);

      if (data) {
        $ret.find('.item-sum').val(data.pullTotal).removeClass('error');
        $ret.find('.item-coupon').val(data.couponId).removeClass('error');
        $ret.find('.item-quantity').val(data.couponQty).removeClass('error');
      }

      $ret.appendTo($sumList);

      return $ret;
    }

    $sumList.on('change', '.item-coupon', function () {
      var $this = $(this);
      if ($this.val()) {
        $this.removeClass('error');
      } else {
        $this.addClass('error');
      }
    });

    // 验证规则
    var $validataPull = $formPull.validate({
      rules: {
        status: { required: true },
        couponQty: { required: true, min: 1, max: 100000 },
        strategyStatus: { required: true },
        remark: { maxlength: 200 }
      },
      errorPlacement: function (error, element) { // 错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); // 这里的element是录入数据的对象
      }
    });

    // // 检测优惠券数量的输入
    // $formPull.on('change keyup', '.item-sum, .item-quantity', function () {
    //   var $this = $(this);
    //   var val = $this.val();
    //   if (/^[1-9]\d{0,4}$/.test(val)) {
    //     $this.removeClass('error');
    //   } else {
    //     $this.addClass('error');
    //   }
    // });

    // 保存操作
    function savePullData() {
      var configKid = preData && preData.kid || '';
      var url = ajaxURL.COUPON + (configKid ? '/coupon/v1/pullConfig/modifyPullConfig' : '/coupon/v1/pullConfig/addPullConfig');
      var data = util.formData($formPull);
      var postData = {
        configKid: configKid,
        couponId: data.couponId,
        couponQty: data.couponQty,
        status: data.status,
        strategyStatus: data.strategyStatus,
        remark: data.remark
      };

      if (configKid) {
        postData.updateId = oUser.userId;
      } else {
        postData.createId = oUser.userId;
      }
      postData.updateBy = oUser.account;

      if ($validataPull.form()) {
        if ($formPull.find('.error').filter(':visible').length > 0) {
          return util.tip.warn('请修正输入错误后再进行提交');
        }
        // 提取优惠券列表信息
        var couponDetailList = [];
        $newList.find('.item-id:checked').each(function () {
          var $this = $(this);
          var kid = $this.parents('li').data('kid');
          var $input = $this.parent().next();
          couponDetailList.push({
            couponId: kid,
            couponQty: $input.val()
          });
        });
        postData.couponDetailList = couponDetailList;

        var pullRuleList = [];
        $sumList.children().each(function () {
          var $this = $(this);
          var pullTotal = $this.find('.item-sum').val();
          var couponId = $this.find('.item-coupon').val();
          var couponQty = $this.find('.item-quantity').val();
          pullRuleList.push({
            pullTotal: pullTotal,
            couponId: couponId,
            couponQty: couponQty
          });
        });

        if (+data.strategyStatus) {
          postData.pullRuleList = pullRuleList;
        } else {
          postData.pullRuleList = [];
        }

        layer.confirm('确定提交当前数据？', function () {
          util.post(url, postData, function (res) {
            getInfo(function () {
              util.tip.success('保存成功');
            });
          });
        });

      }
    }

  });

})(window, jQuery);
